

//
//  CXPictureView.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/27.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

let pictureCellID = "pic_cell"
class CXPictureView: UICollectionView {

    lazy var pictures = [UIImage]()
    /// 添加图片的回调
    var addPicBlock: (() -> Void)?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = UIColor.whiteColor()
        
        let pictureMargin: CGFloat = 5
        let pictureWH: CGFloat = (SCREENW - 2 * CXComposePictureMargin - 2 * pictureMargin) / 3
        
        registerClass(CXPictureViewCell.self, forCellWithReuseIdentifier: pictureCellID)
        
        let flowlayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowlayout.itemSize = CGSize(width: pictureWH, height: pictureWH)
        flowlayout.minimumLineSpacing = pictureMargin
        flowlayout.minimumInteritemSpacing = pictureMargin
        
        //别忘了设置数据源还有代理方法 ！！！！！！！！
        delegate = self
        dataSource = self

        
    }
}
// MARK: - 各种操作
extension CXPictureView {
    
    func addPicture(image: UIImage) {
        
        pictures.append(image)
        hidden = false
        //刷新数据
        reloadData()
    }
}
// MARK: - collectionView's dataSource & delegate
extension CXPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (pictures.count > 0 && pictures.count < 9) ? pictures.count + 1 : pictures.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! CXPictureViewCell
        if indexPath.item == pictures.count {
            cell.image = nil
        } else {
            //TODO: 待补充
            cell.image = pictures[indexPath.item]
            cell.deleteOp = { [unowned self] in
                
                let indexpath = self.indexPathForCell(cell)!
                self.pictures.removeAtIndex(indexpath.item)
                //刷新数据
                collectionView.reloadData()
                collectionView.hidden = (self.pictures.count == 0)
            }
        }
        //由于collectionView下cell没有选中样式这个属性 因此要借助代理方法来实现
//        cell.selectionStyle = .None
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //取消掉默认选中样式
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //防止点击非添加区域的cell时 依然可以添加图片
        if indexPath.item != pictures.count {
            return
        }
        addPicBlock?()
    }
}


private class CXPictureViewCell: UICollectionViewCell {
    /// 图片
    var image: UIImage? {
        
        didSet {
            //TODO: 待完善
            if image == nil {
                imageview.image = UIImage(named: "compose_pic_add")
                imageview.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deletBtn.hidden = true
            } else {
                imageview.image = image
                //这一步很关键 否则之后的非添加cell依然拥有高亮图片
                imageview.highlightedImage = nil
                deletBtn.hidden = false
            }
        }
    }
    /// 删除操作block
    var deleteOp: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 懒加载图片框
    private lazy var imageview: UIImageView = {
        let imageV = UIImageView()
        //不留占位图片?
        return imageV
    }()
    /// 删除按钮
    private lazy var deletBtn: UIButton = {
       
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        //添加点击事件
        button.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
        button.sizeToFit()
        return button
    }()
}
// MARK: - 设置UI
extension CXPictureViewCell {
    
    private func setupUI() {
        
        contentView.addSubview(imageview)
        contentView.addSubview(deletBtn)
        
        imageview.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        deletBtn.snp_makeConstraints { (make) -> Void in
            make.top.trailing.equalTo(contentView)
        }
    }
}
// MARK: - 各种点击事件
extension CXPictureViewCell {
    
    @objc private func deleteBtnClick() {
        deleteOp?()
    }
}